package com.example.systemwork.entity;

import com.example.systemwork.common.entity.LogicEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

@Entity
@Getter
@Setter
@Where(clause = "is_deleted = 0")
public class Shop extends LogicEntity {
    private String shopName;
    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = {"shops","items"})
    private Business business;

    @OneToMany(mappedBy = "shop",
            fetch = FetchType.LAZY,
            orphanRemoval = true,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"shop","lineItems"})
    private Set<Torder> torders;
//
    @OneToMany(mappedBy = "shop",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"shop","item"})
    private Set<ShopItem> shopItems;

    private Boolean isInShop(Item item){
        AtomicReference<Boolean> result=new AtomicReference<>(false);
        shopItems.forEach(shopItem -> {
            if(shopItem.getItem().equals(item)){
                result.set(true);
            }
        });
        return result.get();
    }

    public ShopItem PutOnItem(Item item){
        AtomicReference<ShopItem> result=new AtomicReference<>(null);
        if(isInShop(item)!=true){
            ShopItem shopItem=new ShopItem();
            shopItem.setStatus(1);
            shopItem.setItem(item);
            shopItem.setItemName(item.getItemName());
            shopItem.setPrice(item.getPrice());
            shopItem.setShop(this);
            shopItems.add(shopItem);
            result.set(shopItem);
        }
        return result.get();
    }

    public ShopItem changeStatus(ShopItem Item,Integer status){
        AtomicReference<ShopItem> result=new AtomicReference<>(null);
        shopItems.forEach(shopItem -> {
            if(shopItem.getItem().equals(Item)){
                shopItem.setStatus(status);
                result.set(shopItem);
            }
        });
        return result.get();
    }
}
